Simple
must be in Simple.java
//
and /* */
private
/public
), that it is a Java class (class
), and its name (simple
).public class Simple {}
Java statements, curly braces, comments, and Java framework code don’t need semicolons.
The console window displays only text.
System.out.println("Programming is fun!");
System
class’s \to out
object’s \to println
method to output text to standard output.println
Appends a newline (\n
) while print
does notThe standard input device is typically the keyboard
Char | Name | Description |
---|---|---|
\n | newline | Advances cursor to next line |
\t | tab | Causes cursor to skip to next tab stop |
\b | backspace | Causes cursor to back up, or move left, one position |
\r | carriage return | Causes cursor to go to beginning of current line |
\\ | backslash | Causes a backslash to be printed |
\' | single quote | Causes a single quotation mark to be printed |
\" | double quote | Causes a double quotation mark to be printed |
With these escape sequences, complex text output can be achieved.
public class Variable
{
public static void main(String[] args)
{
int value; // Variable declaration
= 5; // Assignment statement (stores '5' in memory)
value System.out.print("The value is "); // "The value is " is a string literal
System.out.println(value); // Prints the integer '5'
}
}
+
Operator+
can be used two ways:
5 + 5
, yields 10
+
operator is a String
, the result will be a String
."5" + 5
, yields "55"
Warnings on String Literals:
Identifiers: Programmer-defined names that represent classes, variables, or methods
int numberStudents
rather than int nS
)a-z
, A-Z
, 0-9
, _
, or $
)Naming Conventions:
Primitive Data Type: The type of data the variable can hold
Numeric Data Types: | Name | Size | Range | | — | — | — | | byte | 1 byte | Integers in range -128 to 127 | | short | 2 bytes | Integers in the range -32768 to 32767 | | int | 4 bytes | Integers in the range -2147483648 to 2147483647 | | long | 8 bytes | Integers in the range -9223372036854775808 to 9223372036854775807 | | float | 4 bytes | | | double | 8 bytes | |
Tip: You can declare several variables of the same type like so:
int length, width, area
Data types that allow fractional values.
Java Floating-Point Data Types:
float
: Single-precision, 7 decimal pointsdouble
: Double precision, 15 decimal pointsNote: Remember to append
F
to a float.
boolean
Data TypeCan have two possible values: true
or false
.
boolean bool;
= true; bool
char
Data TypProvides access to single characters
char
literals are enclosed in single quotation markschar letter;
= 'A'; letter
char letter = 65;
System.out.println(letter); // Prints 'A'
final
Variables whose value cannot be changed (read-only).
final double INTEREST_RATE = 0.069;
Scanner
ClassDefined in java.util
, allows reading input from the keyboard.
Imported like so:
import java.util.Scanner;
Scanner objects work with System.in
, the standard input device.
// Create Scanner object
Scanner keyboard = new Scanner(System.in);
Scanner
class methods to return input as a …:
nextByte()
: BytenextDouble()
: DoublenextFloat()
: FloatnextInt()
: Intnext()
: String (until the first space)nextLine()
: String (the entire input)nextLong()
: LongnextShort()
: ShortNote: Remember to close a Scanner object to prevent memory leaks.
- e.g.,
input.close();
Assignment Operator (=
): Stores a value in a variable
More on variables:
Java has five arithmetic operators:
| Operator | Meaning |
| — | — |
| +
| Addition |
| -
| Subtraction |
| *
| Multiplication |
| /
| Division |
| %
| Modulus |
Operator | Meaning |
---|---|
- | Negation |
Integer division is truncated. Pay attention to types.
e.g.,
double number = 5/2;
System.out.println(number); // Prints "2.0"
= 5.0/2;
number System.out.println(number); // Prints "2.5"
Operator | Associativity | Example | Result |
---|---|---|---|
- | Right to left | x = -4 + 3 | -1 |
* / % | Left to right | x = -4 + 4 % 3 * 13 + 2 | 11 |
+ - | Left to right | x = 6 + 3 - 4 + 6 * 3 | 23 |
Math
ClassJava’s Math
class contains useful methods for complex mathematical operations. e.g.,
Math.pow()
Math.sqrt()
Math.max()
Math.abs()
Math.abs()
Math.min()
Math.log10()
Predefined \pi:
Math.PI
Allow programmer to perform arithmetic and assignment with a single operator.
Operator | Example |
---|---|
+= | x+=5 |
-= | y-=2 |
*= | z*=10 |
/= | a /=b |
%= | c %=3 |
Java performs some conversions between data types automatically if the conversion will not result in the loss of data.
int x;
double y = 2.5;
= y; // Compile error! (data loss) x
int x;
short y = 2;
= y; // This is fine x
Ranking of numeric data types (Java automatically converts smaller to larger, this is called the widening operation):
double
float
long
int
short
byte
If you need to perform the narrowing conversion, you need to use the cast operator.
= (TARGET_DATA_TYPE) number; TARGET_DATA_TYPE x
Java performs promotion automatically when operands are of different data types.
sum
is a float
and count
is an int
, the value of count
is converted to a float
to perform the following calculation: result = sum / count
String
ClassString
is not a primitive data type, it is a class from the Java standard library.
String
is uppercase because it is a class.Primitive variables actually contain the value they’ve been assigned.
Objects (instances of classes) aren’t stored in variables. Objects are referenced by variables.
String
Objects// Easy string object creation and assignment
String value = "Hello";
// Standard way to create objects
String value = new String("Hello");
String
objects are immutable.name
and otherName
reference the same String
objects.String name = "Hello";
String otherName = "Hello"
length()
charAt(index)
toLowerCase()
toUpperCase()
Scope: The part of a program that has access to a variable’s contents.
main
method are local variablesStyle | Description |
---|---|
// | Single line comment. |
/* ... */ | Block comment. |
/** ... */ | Javadoc comment. |
Note on Javadoc comments: Allows comments to be documented by the javadoc utility. Can be built into HTMl documentation.
- e.g.,
javadoc <source_code.java>
createdindex.html
and several documentation files in the same directory as the input file.
Although the compiler doesn’t care about white space, humans do!
Programs should use proper indentation.
Dialog Boxes: Small graphical window that displays a message to the user or requests input.
JOptionPane
class.JOptionePane
can be imported via: import javax.swing.JOptionPane;
Parse Methods: Method that converts a String
to a number.
Integer
class has a method that converts a String
to an int
.int x = Integer.parseInt("2599");
float y = Float.parseFloat("12.3");
// etc...